/* typehints:start */
import { GameRoot } from "../../root";
/* typehints:end */

import { animRemoveElement, getArcPoint, getObjectType, makeDiv, waitNextFrame } from "../../../core/utils/utils";
import { BaseHUDPart } from "../base_hud_part";
import { DynamicDom } from "../dynamic_dom";
import { globalConfig } from "../../../config/global";
import { SelectBtnGroup } from "../select_btn_group";
import { getSkillLevelTitle } from "../../defines/skill_level_define";

export class HUDBattlePage extends BaseHUDPart{
  constructor(root){
    super(root);
  }

  createElements(parent){
    this.element = makeDiv(parent, 'battle_page', ['hud_page', 'battle_page'], `
      <header>
        <div class="left">开始战斗</div>
        <div class="time">时间: <span>00:00</span></div>
      </header>

      <div class="info">
        <div class="buffs"></div>
        <div class="site">战斗场地信息</div>
      </div>

      <div class="content">
        <svg id="battle-svg">
        </svg>
        <div class="me-units"></div>
        <div class="enemey-units"></div>
      </div>

      <div class="select-skill">
        <div class="cancel-skill styledButton danger">取消释放</div>
        <div class="confirm-skill styledButton">确认释放</div>
      </div>

      <div class="controls">
        <div class="select-btns"></div>
        <div class="pages">
          <div class="page skill-page"></div>
          <div class="page item-page"></div>
          <div class="page action-page">
            <div class="step-skill styledButton">跳过回合</div>
          </div>
        </div>
      </div>
    `);
  }
  
  initialize(){
    this.domAttach = new DynamicDom(this.root, this.element);

    this.trackClicks(this.element.querySelector('header .left'), () => {
      this.root.hud.parts.logBoard.internalShow();
    })

    this.trackClicks(this.element.querySelector('.cancel-skill'), () => {
      this.handleSkillCancel();
    })

    this.trackClicks(this.element.querySelector('.step-skill'), () => {
      this.root.battleMgr.runAction();
    })

    this.trackClicks(this.element.querySelector('.confirm-skill'), () => {
      if(this.root.battleMgr.actionUnit.action.targets.length <= 0){
        this.root.gameState.dialogs.showInfo('请选择单位', '请你选择目标单位，否则该技能无法释放');
      } else {
        this.root.battleMgr.runAction();
      }
    })

    // debug：创建一个战斗
    if(globalConfig.debug.createBattle){
      let npc = this.root.worldMap.npcs.find(item => item.getName() == globalConfig.debug.createBattle);

      if(npc){
        waitNextFrame().then(() => {
          this.root.battleMgr.newBattle(npc);
        })
      }
    }
  }

  handleSelectUnits(unit){
    let action = this.root.battleMgr.actionUnit.action;
    let index = action.targets.indexOf(unit);

    if(index > -1){
      unit.selectTip.text = '';
      action.targets.splice(index, 1);
    } else if(action.skill.getTargetNum() > action.targets.length){
      action.targets.push(unit);
    } else {
      let u = action.targets.splice(0, 1);
      u[0].selectTip.text = '';
      action.targets.push(unit);
    }

    action.targets.map((item, i) => {
      item.selectTip.text = action.skill.getTip(i) || '已选中';
    })
  }

  // 取消技能释放
  handleSkillCancel(){
    this.root.battleMgr.actionUnit.deleteAction();
    this.root.battleMgr.isPlayerSelectTarget = false;
    this.element.classList.remove('player-cancel');
    this.element.classList.add('player-control');
  }

  // 显示玩家操作
  showPlayerControl(){
    this.element.classList.remove('player-cancel');
    this.element.classList.add('player-control');
    this.drawUnitSkill();
  }

  // 隐藏玩家操作
  hidePlayerControl(){
    this.element.classList.remove('player-cancel');
    this.element.classList.remove('player-control');
  }

  hanldeHide(){
    this.domAttach.internalDetach();
  }

  handleShow(){
    this.domAttach.internalAttach();
    
    this.drawPlayerControl();
    this.drawUnits();
  }

  drawPlayerControl(){
    this.selectBtns = new SelectBtnGroup(this.root, this.element, '.select-btns', [
      {
        text: '神通',
        classType: 'item',
        active: true,
        page: '.pages|skill-page'
      },
      {
        text: '物品',
        classType: 'item',
        page: '.pages|item-page'
      },
      {
        text: '操作',
        classType: 'item',
        page: '.pages|action-page'
      },
    ]);
  }

  drawUnits(){
    let meParent = this.element.querySelector('.me-units');
    let enemeyParent = this.element.querySelector('.enemey-units');

    this.root.battleMgr.getAllUnit().map(item => {
      let parent = item.type == 'me' ? meParent : enemeyParent;

      parent.appendChild(item.element);
    })
  }

  // 滚动到指定元素
  scrollToIndex(unit){
    // 移动位置到指定的单位
    let content = this.element.querySelector('.content');
    let scrollTop = unit.element.offsetTop - content.offsetTop - 100;

    if(unit.type == 'me'){
      setTimeout(() => {
        content.scrollTop = scrollTop;
      }, 300);
    } else {
      content.scrollTop = scrollTop;
    }
  }

  drawSvgLine(actionUnit, targetUnits){
    let battleSvg = this.element.querySelector('#battle-svg');

    targetUnits.map(targetUnit => {
      let path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
      let posArr = [
        [actionUnit.element.offsetWidth / 2, actionUnit.element.offsetTop + actionUnit.element.offsetHeight / 2],
        [targetUnit.element.offsetWidth / 2, targetUnit.element.offsetTop + targetUnit.element.offsetHeight / 2]
      ];
      if(actionUnit.type == 'enemy'){
        posArr[0][0] += actionUnit.element.offsetLeft;
      } else {
        posArr[1][0] += targetUnit.element.offsetLeft;
      }
  
      let AnglePos = getArcPoint(posArr[0], posArr[1], 20);
      path.setAttribute('d', `M${posArr[0].join(' ')} Q${AnglePos[0].join(' ')} ${posArr[1].join(' ')}`)
      battleSvg.appendChild(path);
      animRemoveElement(path, () => {
        battleSvg.removeChild(path);
      }, 1000)
    })
  }

  // 绘制所有技能 
  drawUnitSkill(){
    let actionUnit = this.root.battleMgr.actionUnit;
    let skills = actionUnit.people.getSkills();
    let parent = this.element.querySelector('.skill-page');
    this.selectBtns.setActive();

    parent.innerHTML = '';

    skills.map(skill => {
      let tagsText = '';
  
      skill.internalGetTags().map(tag => {
        tagsText += `
          <div class="tag ${tag.type}">
            ${tag.img ? `<img src="${tag.img}">` : ''}
            ${tag.text}
          </div>
        `
      });

      let isShowSkillDesc = !this.root.app.setting.getSetting('battleCutSkillDesc');

      let dom = makeDiv(parent, '', ['item', 'skill'], `
        <div class="title">
          ${skill.getName()}[${getSkillLevelTitle(skill.num)}]
        </div>
        ${
          isShowSkillDesc ? `
            <div class="min-text">
              ${skill.getDesc()}
            </div>
            <div class="tag-text">
              ${tagsText}
            </div>
          ` : ''
        }
      `);

      this.trackLongPressAndClick(dom, () => {
        
      }, () => {
        let flag = skill.internalGetIsUse(this.root.battleMgr.actionUnit.people);

        if(getObjectType(flag) == 'String') {
          this.root.gameState.dialogs.showWarning('无法使用', flag);
        } else {
          skill.getData().then(data => {
            this.clickSkill(skill, data);
          })
        }
      })
    })
  }

  clickSkill(skill, data = {}){
    // 选择技能并选定目标
    this.element.classList.remove('player-control');
    this.element.classList.add('player-cancel');

    let targets = [];
    let isPlayerControl = skill.getIsPlayerSelectTarget();

    // 如果目标只有一个的话，那么只能对自己释放
    if(skill.getTargetNum() <= 0){
      targets = [actionUnit];
    } else if(!isPlayerControl){
      targets = skill.getTargets();
    }

    this.root.battleMgr.actionUnit.action = { skill, targets, data };
    this.root.battleMgr.isPlayerSelectTarget = true;

    if(!isPlayerControl){
      this.root.battleMgr.runAction();
    }
  }
}